package com.guoxin.concurrentcy.chapter10;

import java.util.concurrent.TimeoutException;
import java.util.stream.Stream;

public class LockTest {
    public static void main(String[] args) {
        BooleanLock booleanLock = new BooleanLock();

        Stream.of("T1", "T2", "T3", "T4").forEach(name -> new Thread(() -> {
            try {
                booleanLock.lock(1000);
                System.out.println(Thread.currentThread().getName() + "获得了锁");
                work();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                System.out.println(e.getMessage());
            } finally {
                booleanLock.unlock();
            }
        }, name).start());
    }

    public static void work() {
        try {
            System.out.println(Thread.currentThread().getName() + " is working");
            Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
